package com.liyiruo.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/4/11 下午3:17
 */
public class XMLUtils {
    /**
     *
     * @param xml
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T xml2Obj(String xml, Class<T> clazz) {

        T obj = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(xml);
            obj = clazz.newInstance();
            obj = (T) unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
